<%@ page import="com.example.dao.UserDao" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="com.example.util.DBUtil" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // 检查是否为POST请求
    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    request.setCharacterEncoding("UTF-8");
    
    // 获取表单参数
    String username = request.getParameter("username");
    String realname = request.getParameter("realname");
    String password = request.getParameter("password");
    String email = request.getParameter("email");
    String phone = request.getParameter("phone");

    // 验证必填字段
    if (username == null || username.trim().isEmpty() ||
        password == null || password.trim().isEmpty() ||
        email == null || email.trim().isEmpty()) {
        
        request.setAttribute("error", "用户名、密码和邮箱是必填项");
        request.getRequestDispatcher("user_add.jsp").forward(request, response);
        return;
    }

    try {
        // 检查用户名是否已存在
        UserDao userDao = new UserDao();
        if (userDao.userExists(username)) {
            request.setAttribute("error", "用户名已存在");
            request.getRequestDispatcher("user_add.jsp").forward(request, response);
            return;
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setRealname(realname);
        user.setPassword(password); // 实际项目中应该加密密码
        user.setEmail(email);
        user.setPhone(phone);

        // 保存到数据库
        userDao.createUser(user);

        // 重定向到用户列表页面
        response.sendRedirect("user_list.jsp?message=用户添加成功");
    } catch (Exception e) {
        request.setAttribute("error", "添加用户失败: " + e.getMessage());
        request.getRequestDispatcher("user_add.jsp").forward(request, response);
    }
    return;
%>
<html>
<head>
    <title>添加用户结果</title>
    <link rel="stylesheet" href="../assets/css/styles.css">
    <link rel="stylesheet" href="../assets/css/menu.css">
    <style>
        /* 后台管理系统特有的样式 */
        .search-bar {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        .search-input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>添加用户结果</h1>
    </div>
</div>
</body>
</html>